<?php
declare (strict_types = 1);

namespace app\http\middleware;
use app\common\model\User;
use app\common\model\UserToken;
use app\Request;
use app\services\jwt\JwtService;


class CheckToken
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle(Request $request, \Closure $next)
    {
        if(is_null($request->header('Authorization'))){
            return error('未登录',[],'204');
        }
        if(empty($request->header('Authorization'))){
            return error('未登录',[],'204');
        }
        $token = trim($request->header('Authorization'));

        //没有token
        if (!$token){
            return error('未登录',[],'204');
        }
        //没有找到jwt类
        $jwt=new JwtService();
       try {
            $decode=$jwt->checkToken($token);
       }catch (\Exception $e){
            return error('登录已过期，请重新登录',[],'204');
        }
        //解析token
        $decode=json_decode(json_encode($decode),true);


        $authInfo = UserToken::where(['uid'=> $decode['uid'] ,'type' => 1])->order('effective_time','desc')->find();

        if(!$authInfo){
            return error("登录状态有误,请重新登录",[],'204');
        }
        if ($token !== $authInfo['token']){
            return error("token已过期",[],'204');
        }
        User::where('id', $decode["uid"])->update(['is_online' => 1]);
        $user = User::where('id', $decode["uid"])->find();


        if(!$user){
            //$authInfo->delete();
            return error("登录状态有误,请重新登录",[],'204');
        }
        if (!$decode){
            //$authInfo->delete();
            return error("登录状态有误,请重新登录",[],'204');
        }
      /*  if (time() > $decode['nbf']){
            //$authInfo->delete();
            return error("登录状态有误,请重新登录",[],'204');
        }*/
        $request->userInfo = $user;

        return $next($request);
    }
}
